// 添加记录页逻辑
Page({
  data: {
    form: {
      amount: '',
      rate: '0.003',
      party: '',
      status: '0',  // 默认为处理中
      type: 'expense'
    },
    result: 0,
    // 状态文本映射
    statusText: {
      '0': '处理中',
      '1': '已完成',
      '2': '已取消'
    },
    // 类型文本映射
    typeText: {
      'expense': '支出',
      'income': '收入'
    }
  },

  // 输入变化处理
  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    let value = e.detail.value;

    // 处理状态选择器的特殊情况
    if (field === 'status' && typeof value === 'number') {
      // 将选择器索引转换为状态值
      const statusValues = ['0', '1', '2'];
      value = statusValues[value];
    }

    this.setData({
      [`form.${field}`]: value
    });

    if (field === 'amount' || field === 'rate') {
      this.calculateResult();
    }
  },

  // 计算结果
  calculateResult() {
    const { amount, rate } = this.data.form;
    if (amount && rate) {
      const amountNum = parseFloat(amount);
      const rateNum = parseFloat(rate);
      const result = amountNum - (amountNum * rateNum);
      this.setData({ result: result.toFixed(2) });
    }
  },

  // 保存记录
  submitForm() {
    const { form, result } = this.data;
    if (!form.amount || !form.party) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    const newRecord = {
      id: Date.now(),
      amount: parseFloat(result),
      rate: parseFloat(form.rate),
      originalAmount: parseFloat(form.amount),
      party: form.party,
      status: form.status,
      type: form.type,
      date: new Date().toISOString().split('T')[0]
    };
    console.log('新增记录:', newRecord);

    // 保存到本地存储
    const transactions = wx.getStorageSync('transactions') || [];
    transactions.unshift(newRecord);
    wx.setStorageSync('transactions', transactions);

    // 获取当前页面栈
    const pages = getCurrentPages();
    // 获取上一页实例
    const prevPage = pages[pages.length - 2];
    // 调用上一页的刷新方法
    if (prevPage && prevPage.loadTransactions) {
      prevPage.loadTransactions();
    }

    // 返回上一页
    wx.navigateBack({
      success: () => {
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        });
      }
    });
  }
})
